<?php

namespace App\Http\Controllers;

use App\Models\Pay;
use App\Models\Trade;
use Illuminate\Http\Request;
use Excel;
use Illuminate\Support\Facades\DB;

class ImportController extends AdminController
{

    public $ret=array();
   public function  index(Request $request){

       if($request->isMethod("post")){
           $allowed_extensions=["xls",'xlsx'];



           $msg = array();
           $ret = array();

           if ($request->file('file')->getClientOriginalExtension() && !in_array($request->file('file')->getClientOriginalExtension(), $allowed_extensions)) {
                    $msg[]="上传文件格式错误";
           }else {

               $file = time().'.'.$request->file('file')->getClientOriginalExtension();
//               if($_SERVER["REMOTE_ADDR"]=='127.0.0.1'){
//                   $dir='E:/xampp/htdocs/totleagent/storage/';
//               }else{
//                   $dir='/home/forge/totleagent.tonglingdi.cn/storage/';
//               }

               $dir=storage_path();

               $request->file('file')->move($dir, $file);

               Excel::load(storage_path($file), function($reader) {
                   
                   $data = $reader->toArray();
//                   dd($data);

                   $str= '';
                   foreach ($data as $key =>$val){
                       unset($data[$key][0]);
                       $str.= end($data[$key]);
                   }
                   $html = $this->get_td_array($str);
                   $length = strrpos($html[0][0],":");
                   $tranid =  substr($html[0][0], $length+1);


                   unset($html[0]);
                   unset($html[1]);
                   $data=array();
                   $ticket=array();
                   foreach ($html as $val){
                       if(is_numeric($val[0])){
//                           dd($val);
                           $ticket[]=$val[0];
                           $data[$val[0]]=array(
                               'tranid'=>$tranid,
                               'ticket'=>isset($val[0])?$val[0]:'',
                               'starttime'=>isset($val[1])?$val[1]:'',
                               'type'=>isset($val[2])?$val[2]:'',
                               'size'=>isset($val[3])?$val[3]:'0',
                               'item'=>($val[2]=='balance')?"":(isset($val[4])?$val[4]:''),
                               'startprice'=>isset($val[5])?$val[5]:'0',
                               's/l'=>isset($val[6])?$val[6]:'0',
                               't/p'=>isset($val[7])?$val[7]:'0',
                               'endtime'=>isset($val[8])?$val[8]:'0',
                               'endprice'=>isset($val[9])?$val[9]:'0',
                               'commission'=>isset($val[10])?$val[10]:'0',
                               'profit'=>($val[2]=='balance')?$val[4]:(isset($val[13])?$val[13]:'0'),
                               'created_at'=>date("Y-m-d H:i:s")
                           );

                       }else{
                           break;
                       }
                   }

                   $t =  Trade::whereIn("ticket",$ticket)->get(["ticket"]);
                   if(count($t)){
                       foreach ($t as $val){
                           unset($data[$val->ticket]);
                       }
                       $this->ret=array(
                            'yes'=>'有效数据'.count($data).'条',
                           'repeat'=>'重复数据'.count($t)."条"
                       );
                   }else{
                       $this->ret=array(
                           'yes'=>'有效数据'.count($data).'条',
                           'repeat'=>'无重复数据'
                       );
                   }

                   if(!empty($data)){
                       Trade::insert($data);
                       $this->setlog(json_encode($data),'导入用户的操作记录');
                   }
               })->get();
           }

           unlink(storage_path($file));

           if(!empty($msg)){
               return redirect("/import")
                   ->withErrors($msg)
                   ->withInput();
           }else{

               return redirect("/import")->with("messages", ['0' => "数据导入成功",'1'=>$this->ret['yes'],'2'=>$this->ret['repeat']]);
           }



       }else{
           return view("import.add");
       }


   }

    /**
    * 对象 转 数组
    *
    * @param object $obj 对象
    * @return array
    */
public function object_to_array($object) {
    $array=array();
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
   }

    public function  get_td_array($table) {
        $table = preg_replace("'<table[^>]*?>'si","",$table);
        $table = preg_replace("'<tr[^>]*?>'si","",$table);
        $table = preg_replace("'<td[^>]*?>'si","",$table);
        $table = str_replace("</tr>","{tr}",$table);
        $table = str_replace("</td>","{td}",$table);
        //去掉 HTML 标记
        $table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table);
        //去掉空白字符
        $table = preg_replace("'([rn])[s]+'","",$table);
        $table = str_replace(" ","",$table);
        $table = str_replace(" ","",$table);
        $table = explode('{tr}', $table);
        array_pop($table);
        foreach ($table as $key=>$tr) {
            $td = explode('{td}', $tr);
            array_pop($td);
            $td_array[] = $td;
        }
        return $td_array;
    }

}
